﻿/**
 * The AudioTrack Library by Chris J. Rock. Aug 10, 2011
 * Check out chrisjrock.net and be a king among men.
 *
 * Copyright (c) 2011 Chris J. Rock
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/


package net.chrisjrock.sound.audioTrack.mixer 
{
	import flash.events.Event;
	
	import net.chrisjrock.sound.audioTrack.events.AudioTrackEvent;
	import net.chrisjrock.sound.audioTrack.track.IAudioTrack;
	import net.chrisjrock.sound.audioTrack.track.IPlayableTrack;
	
	/**
	 * Acts as a mixer to queue multiple tracks as in a playlist. Because the child tracks are played linearly, this mixer also behaves as a playable track.
	 * @author Christopher J. Rock
	 */
	public class QueueTrack extends AbstractMixer implements IPlayableTrack
	{
		private var _tracks:Vector.<IPlayableTrack> = new Vector.<IPlayableTrack>();
		
		private var _trackNum:int;
		private var _currentTrack:IPlayableTrack;
		private var _playing:Boolean;
		
		private var _loops:int;
		private var _loopInfinitely:Boolean;
		
		public function QueueTrack (trackId:String)
		{
			super(trackId);
		}
		
		/**
		 * @inheritDoc
		 */		
		override public function dispose():void 
		{
			if (_tracks)
			{
				stop();
				var i0:int = _tracks.length - 1;
				for (; i0 >= 0 ; i0--)
				{
					removeTrack(_tracks[i0]);
				}
				_tracks = null;
			}
			
			super.dispose();
		}
		
		/**
		 * @inheritDoc
		 */		
		override public function disposeAll ():void 
		{
			stop();
			
			if (_tracks)
			{
				var trackNum:int = _tracks.length - 1;
				for (; trackNum >= 0 ; trackNum--)
				{
					if (_tracks[trackNum] is IAudioMixer)
					{
						IAudioMixer(_tracks[trackNum]).disposeAll();
					}
					else
					{
						_tracks[trackNum].dispose();
					}
				}
				_tracks = null;
			}
			
			super.dispose();
		}
		
		//TODO: addTrack is called redundantly when a track's mixer property is set to 'this'. Tracks like this one might work better if that were not the case.
		/**
		 * @inheritDoc
		 */		
		override public function addTrack (track:IAudioTrack):void 
		{
			if (!(track is IPlayableTrack))
			{
				throw (new Error("Only tracks of type IPlayableTrack can be added. Attempted to add '" + track + "'."));
			}
			
			super.addTrack(track);
		}
		
		/**
		 * @inheritDoc
		 */		
		override public function hasTrack (track:IAudioTrack):Boolean
		{
			if (_tracks == null)
			{
				throw (new Error("Track list has been destroyed."));
			}
			
			if (!(track is IPlayableTrack))
			{
				return false;
			}
			
			var index:int = _tracks.indexOf(track);
			return index >= 0;
		}
		
		/**
		 * @inheritDoc
		 */		
		public function stop ():void 
		{
			if (!_playing) 
			{
				return;
			}
			
			_currentTrack.stop();
			_currentTrack.removeEventListener(AudioTrackEvent.AT_END , trackCompleteHandler);
			_playing = false;
			_trackNum = 0;
			dispatchEvent(new AudioTrackEvent(AudioTrackEvent.AT_START));
			dispatchEvent(new AudioTrackEvent(AudioTrackEvent.STOP));
		}
		
		/**
		 * @inheritDoc
		 */		
		public function play (restart:Boolean = false):void 
		{
			if (_tracks == null || _tracks.length == 0 || !restart && _playing) 
			{
				return;
			}
			
			_playing = true;
			
			if (_currentTrack) 
			{
				if (_currentTrack.paused && !restart) 
				{
					_currentTrack.play();
					dispatchEvent(new AudioTrackEvent(AudioTrackEvent.PLAY));
					return;
				}
				_currentTrack.stop();
				_currentTrack.removeEventListener(AudioTrackEvent.AT_END , trackCompleteHandler);
			}
			
			if (restart)
			{
				_trackNum = 0;
			}
			
			_currentTrack = _tracks[_trackNum];
			_currentTrack.addEventListener(AudioTrackEvent.AT_END , trackCompleteHandler);
			_currentTrack.play();
			dispatchEvent(new AudioTrackEvent(AudioTrackEvent.PLAY));
		}
		
		/**
		 * @inheritDoc
		 */		
		public function pause():void 
		{
			if (!_playing) 
			{
				return;
			}
			
			_playing = false;
			_currentTrack.pause();
			dispatchEvent(new AudioTrackEvent(AudioTrackEvent.PAUSE));
		}
		
		override protected function addTrackToCollection (track:IAudioTrack):void
		{
			if (_tracks == null)
			{
				throw (new Error("Track list has been destroyed."));
			}
			
			_tracks.push(track);
		}
		
		override protected function removeTrackFromCollection (track:IAudioTrack):void
		{
			if (_tracks == null)
			{
				throw (new Error("Track list has been destroyed."));
			}
			
			var index:int = _tracks.indexOf(track);
			_tracks.splice(index , 1);
		}
		
		private function trackCompleteHandler (event:Event):void 
		{
			_currentTrack.removeEventListener(AudioTrackEvent.AT_END , trackCompleteHandler);
			_currentTrack.stop();
			_currentTrack = null;
			_playing = false;
			
			var continuePlaying:Boolean;
			_trackNum++;
			if (_trackNum < _tracks.length || _loopInfinitely)
			{
				continuePlaying = true;
			}
			else if (_loops > 0)
			{
				_loops--;
				continuePlaying = true;
			}
			
			if (continuePlaying) 
			{
				if (_trackNum >= _tracks.length)
				{
					_trackNum = 0;
				}
				play();
			}
			else
			{
				_loops = 0;
				dispatchEvent(new AudioTrackEvent(AudioTrackEvent.AT_END));
			}
		}
		
		/**
		 * @inheritDoc
		 */		
		public function get playing ():Boolean
		{
			return _playing;
		}
		
		/**
		 * How many times the track will be looped.
		 * @return 
		 * 
		 */		
		public function get loops ():int
		{
			return _loops;
		}
		
		/**
		 * @private
		 */		
		public function set loops (value:int):void 
		{
			if (_loops != value || _loopInfinitely) 
			{
				_loops = value;
				_loopInfinitely = false;
			}
		}
		
		/**
		 * Forces the track to loop infinitely. 
		 * @return 
		 * 
		 */		
		public function get loopInfinitely ():Boolean
		{
			return _loopInfinitely;
		}
		
		/**
		 * @private
		 */		
		public function set loopInfinitely (value:Boolean):void 
		{
			if (_loopInfinitely != value) 
			{
				_loopInfinitely = value;
				if (_loopInfinitely)
				{
					_loops = int.MAX_VALUE;
				}
			}
		}
		
		/**
		 * The number of the track currently being played.
		 * @return 
		 * 
		 */		
		public function get trackNum ():int
		{
			return _trackNum;
		}
		
		/**
		 * @private
		 */		
		public function set trackNum (value:int):void 
		{
			if ((value %= _tracks.length) != _trackNum) 
			{
				stop();
				_trackNum = value;
				play();
			}
		}
		
		/**
		 * Returns the track currently being played. 
		 * @return 
		 * 
		 */		
		public function get currentTrack ():IPlayableTrack
		{
			return _currentTrack;
		}
		
		/**
		 * @inheritDoc
		 */		
		public function get paused ():Boolean
		{
			return !_playing && _currentTrack && _currentTrack.paused;
		}
	}
	
}